/*
 * @Author: your name
 * @Date: 2020-05-07 15:59:54
 * @LastEditTime: 2020-10-30 10:45:43
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /yigo/Router.js
 */
// In App.js in a new project

import React, { Component } from 'react'
import {DeviceEventEmitter, StatusBar } from 'react-native';

import 'react-native-gesture-handler';
import { connect } from 'react-redux'
import Loading from './src/Utils/Loading'
import Storage from './src/Utils/AsyncStorage'
import { Provider } from '@ant-design/react-native';
// import Ionicons from 'react-native-vector-icons/Ionicons'


//用户


//商家
import BusinessOrderListScreen from './src/Pages/Business/BusinessOrderListScreen'
import BusinessRegisterScreen from './src/Pages/BusinessRegisterScreen'
//骑手

//暂时不知道
import OrderStatusListScreen from './src/Pages/OderStatusListScreen'

import { createStackNavigator, TransitionPresets } from '@react-navigation/stack';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import { NavigationContainer, DefaultTheme, useTheme } from '@react-navigation/native';

import LoginScreen from './src/Pages/LoginScreen'
import HomePageScreen from './src/Pages/HomePageScreen'
import MineScreen from './src/Pages/MineScreen'
import OrderListScreen from './src/Pages/OrderListScreen'
import GoodDetailScreen from './src/Pages/GoodDetailScreen'


import SettingScreen from './src/Pages/SettingScreen'
import FineFoodRegisterScreen from './src/Pages/FineFoodRegisterScreen'
import CreateOrderInfoScreen from './src/Pages/CreateOrderInfoScreen'
const Stack0 = createStackNavigator();
const Tab = createBottomTabNavigator();
// const { colors } = useTheme();


// const MyTheme = {
//   dark: false,
//   colors: {
//     primary: '#C78885',
//     background: 'rgb(242, 111, 242)',
//     card: 'yellow',
//     text: 'green',
//     border: '#CD5C5C',
//   },
// };

console.disableYellowBox = true 




class Router extends Component {
  constructor(props) {
    super(props)
  
    this.state = {
       color:'tomato'
    }
    global.themeColor = this.state.color;


  }
  
  /**
   * @description:这里检测是否有缓存的token.进行自动登录操作 
   * @param {type} 
   * @return: 
   */
  componentWillMount = async () => {
      let userInfo = await Storage.get('userInfo');      
      if (userInfo) {
        this.props.refreshToken({userInfo})
      } else {
        this.props.refreshToken({userInfo:''})
      }
  }

  componentDidMount() {
    DeviceEventEmitter.addListener('theme_change',color => {
      this.setState({color})
      global.themeColor = color;
    })
  }
  
  
  render() {
    let {userInfo, isFetch} = this.props
    if (isFetch) return <Loading/>     
    {/* theme={MyTheme}*/}    
    //  initialRouteName='AddContractDetailScreen' 
    const commonParamter = (Widge) => (props) => <Widge {...props} color={this.state.color}/> 
    
    return (
      <Provider>
        <StatusBar barStyle="light-content" translucent={false} backgroundColor={this.state.color}/>
        <NavigationContainer> 
          <Stack0.Navigator  screenOptions={({ route }) => {
            return {
              headerStyle: {
                backgroundColor: this.state.color,
              }, // 一个应用于 header 的最外层 View 的 样式对象
              headerTintColor: 'white', // 返回按钮和标题都使用这个属性作为它们的颜色
              headerTitleStyle: {
                fontWeight: 'bold',
              },
              headerMode:'none',
              headerBackTitleVisible: false,
              headerTitleAlign: 'center',
              cardStyle: {
                flex: 1,
                backgroundColor: '#f5f5f9',
              },
              ...TransitionPresets.SlideFromRightIOS,
  }
          }}>
            {userInfo? 
              (<>
                <Stack0.Screen options={{title:'美食'}} name="TabbarScreen" component={commonParamter(TabbarScreen)}/>
                <Stack0.Screen options={{title:'设置'}} name="SettingScreen" component={commonParamter(SettingScreen)}/>
                <Stack0.Screen options={{title:'注册美食入口'}} name="FineFoodRegisterScreen" component={commonParamter(FineFoodRegisterScreen)}/>
                <Stack0.Screen options={{title:'商品详情'}} name="GoodDetailScreen" component={commonParamter(GoodDetailScreen)}/>
                <Stack0.Screen options={{title:'提交订单'}} name="CreateOrderInfoScreen" component={commonParamter(CreateOrderInfoScreen)}/>

                
                
              </>
              )
              : 
              (<>
              <Stack0.Screen headerMode='none' options={{headerMode:'none'}} name="登  录" component={LoginScreen} />
              <Stack0.Screen options={{title:'商家注册'}} name="BusinessRegisterScreen" component={commonParamter(BusinessRegisterScreen)}/>

              </>)
              } 
          </Stack0.Navigator>
          </NavigationContainer>
        </Provider>
    );
  }
}

const TabbarScreen = (props) => {
  //设置Tabbar item icon  
  const TabBarIcon = ({focused, color, size},route) => {
    let iconName;
        if (route.name === 'HomePageScreen') {
          iconName = focused
            ? 'ios-text'
            : 'ios-text';
        } else if (route.name === 'OrderListScreen') {
          iconName = focused ? 'ios-contacts' : 'ios-contacts';
        } else if (route.name === 'FindScreen') {
          iconName = focused ? 'ios-alarm' : 'ios-alarm';
        } else if (route.name === 'MineScreen') {
          iconName = focused ? 'ios-finger-print' : 'ios-finger-print';
        }
        // You can return any component that you like here!              
        return <></>  
        // return <Ionicons name={iconName} size={size} color={color} />;
  }
  console.log("用户类型:",userInfo.userType);

  //根据登录用户角色设置不同路   
  return (
      <Tab.Navigator
        screenOptions={({ route }) => ({
          tabBarIcon: ({ focused, color, size }) => TabBarIcon({ focused, color, size },route)
        })}
        tabBarOptions={{activeTintColor: props.color,inactiveTintColor: 'gray'}}>
        {userInfo.userType == 0 ?  //用户路由
        <>
        <Tab.Screen name="HomePageScreen" options={{title:'美食'}} listeners={({ navigation, route }) => option({navigation, route})} component={HomePageScreen} />
        {/* <Tab.Screen name="OrderListScreen" options={{title:'订单'}} listeners={({ navigation, route }) => option({navigation, route})} component={OrderListScreen} />   */}
        <Tab.Screen name="MineScreen" options={{title:'我的'}} listeners={({ navigation, route }) => option({navigation, route})} component={MineScreen} /> 
        </> :
        userInfo.userType == 1 ?   //商家路由
        <>
        <Tab.Screen name="OrderStatusListScreen" options={{title:'订单'}} listeners={({ navigation, route }) => option({navigation, route})} component={OrderStatusListScreen} />  
        <Tab.Screen name="MineScreen" options={{title:'我的'}} listeners={({ navigation, route }) => option({navigation, route})} component={MineScreen} /> 
        </> :
        userInfo.userType == 2 ?   //骑手路由
        <>
        <Tab.Screen name="OrderStatusListScreen" options={{title:'订单'}} listeners={({ navigation, route }) => option({navigation, route})} component={OrderStatusListScreen} />  
        <Tab.Screen name="MineScreen" options={{title:'我的'}} listeners={({ navigation, route }) => option({navigation, route})} component={MineScreen} /> 
        </> :  null
        }

      </Tab.Navigator>
  );
}

const option = ({ navigation, route }) => ({
    tabPress: e => {    
      // Prevent default action
      e.preventDefault();
      // Do something with the `navigation` object
      navigation.jumpTo(`${route.name}`);    
      const parent = navigation.dangerouslyGetParent();
      let title = route.name === "HomePageScreen" ? '美食' :
                  route.name === "OrderListScreen" ? '订单' :
                  route.name === "FindScreen" ? '发现' : '我的'
      parent.setOptions({title})
   }
})

const mapStateToProps = (state) => {
  let {userInfo, isFetch} = state.UserInfo.authUserToken || ''
  return {userInfo, isFetch} 
}

const mapDispatchToProps = (dispatch, ownProps) => {
  return {
      refreshToken:(paramter) => dispatch({...paramter,type:'RefreshToken'})
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(Router)
